package com.ikas.ai.server.module.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ikas.ai.consts.Consts;
import com.ikas.ai.enums.MimeTypeEnum;
import com.ikas.ai.handle.JsonResult;
import com.ikas.ai.handle.JsonResultType;
import com.ikas.ai.server.aop.ColumnCheck;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.AbstractBean;
import com.ikas.ai.server.module.system.model.Role;
import com.ikas.ai.server.module.system.model.User;
import com.ikas.ai.server.module.system.model.dto.ChangePasswordDTO;
import com.ikas.ai.server.module.system.model.dto.UpdateUserInfoDTO;
import com.ikas.ai.server.module.system.model.vo.UserRoleVo;
import com.ikas.ai.server.module.system.model.vo.UserVo;
import com.ikas.ai.server.module.system.service.RoleService;
import com.ikas.ai.server.module.system.service.UserService;
import com.ikas.ai.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 系统管理-用户管理
 *
 * @author deng.baohui
 */
@SuppressWarnings("all")
@Validated
@RestController
@RequestMapping("/system/user")
public class UserController extends AbstractBean {


    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${ikas.upload.path}")
    private String filePath;


    private static final String COLUMN_NAMES = "id,userName,createTime";

    /**
     * 用户管理分页查询
     *
     * @return
     * @ColumnCheck(value = COLUMN_NAMES) String sortColumnName
     */
    @GetMapping("/page")
    public String pageQueryUserList(@RequestParam(value = "userName", required = false) String userName,
                                    @RequestParam(value = "phone", required = false) String phone,
                                    @RequestParam(value = "email", required = false) String email,
                                    @RequestParam(value = "createTime", required = false) String[] createTime,
                                    @RequestParam(value = "page", required = false) Integer pageNo,
                                    @RequestParam(value = "size", required = false) Integer pageSize,
                                    @RequestParam(value = "sc", required = false) @ColumnCheck(value = COLUMN_NAMES) String sortColumnName,
                                    @RequestParam(value = "so", required = false) String sortOrder) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        PageUtil.configPageHelper(pageNo, pageSize, sortColumnName, sortOrder, "id", "desc");
        List<UserVo> users = userService.pageQueryUserList(userName, phone, email, createTime);
        PageInfo<UserVo> pageInfo = new PageInfo<>(users);
        jsonResult.add(pageInfo);
        return jsonResult.toJSON();
    }


    /**
     * 查询所有未禁用的用户账号及姓名
     *
     * @return
     */
    @GetMapping("/selectAll")
    public String selectAll() {
        List<JSONObject> userList = userService.getUserList();
        return JsonResult.success(userList);
    }

    /**
     * 新增或修改用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    public String updateOrSaveUser(@RequestBody @Valid User user, BindingResult bindingResult) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        Long id = user.getId();
        //更新操作
        if (id != null && id > 0) {
            User userVo = userService.getById(id);
            if (userVo == null) {
                throw new BusinessException("该用户不存在！");
            }
            if (userVo.getUserName().equals(Consts.ROOT)) {
                jsonResult.setType(JsonResultType.ERROR);
                jsonResult.setMessage("admin账号不允许修改");
                return jsonResult.toJSON();
            }
            //查询新用户名是否被占用
            User quser = userService.getUser(user.getUserName());
            if (quser != null && quser.getId().intValue() != id.intValue()) {
                jsonResult.setType(JsonResultType.ERROR);
                jsonResult.setMessage("用户名已被占用");
                return jsonResult.toJSON();
            }
            userService.updateUser(user);
            redisUtil.deleteKey(Consts.PREFIX_USER_LOGIN + userVo.getUserName());
        } else {
            //查询用户名是否被占用
            User quser = userService.getUser(user.getUserName());
            if (quser != null) {
                jsonResult.setType(JsonResultType.ERROR);
                jsonResult.setMessage("用户名已被占用");
                return jsonResult.toJSON();
            }
            userService.saveUser(user);
        }
        jsonResult.setMessage("操作成功");
        return jsonResult.toJSON();
    }

    /**
     * 修改密码
     *
     * @param changePasswordDTO
     * @return
     */
    @PostMapping("/change/password")
    public JsonResult modifyPassword(@RequestBody ChangePasswordDTO changePasswordDTO) throws Exception {
        userService.changePassword(changePasswordDTO);
        return JsonResult.ok();
    }

    /**
     * 通过id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public String get(@PathVariable("id") Long id) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        User user = userService.getUserById(id);
        user.setPassword(null);
        jsonResult.add(user);
        return jsonResult.toJSON();
    }

    /**
     * 获取角色列表
     *
     * @return
     */
    @GetMapping("/roleList")
    public String roleList() {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        List<Role> roles = roleService.list();
        jsonResult.add(roles);
        return jsonResult.toJSON();
    }

    /**
     * 根据用户id获取用户角色
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("/roleList/{id}")
    public String roleListById(@PathVariable("id") Long userId) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        List<Role> roles = userService.getRoleListById(userId);
        jsonResult.add(roles);
        return jsonResult.toJSON();
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable("id") String id) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        userService.deleteUsers(id);
        return jsonResult.toJSON();
    }

    /**
     * 批量设置用户角色
     *
     * @param userRoleVo
     * @return
     */
    @PostMapping("/setUserRole")
    public String setUserRole(@RequestBody @Valid UserRoleVo userRoleVo, BindingResult bindingResult) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        userService.setUserRole(userRoleVo);
        return jsonResult.toJSON();
    }


    /**
     * 上传头像图片
     *
     * @return
     */
    @PostMapping("/upload_avatar")
    public String uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        try {
            Assert.state(!file.isEmpty(), "图片不能为空");
            // 获取文件名
            long fileSize = file.getSize();
            Assert.state(fileSize / 1024 / 1024 <= 1, "图片大小不能大于1M");

            //获取文件类型
            String suffixName = ImageTypeUtil.getImageType(file.getInputStream());
            String[] imgTypes = new String[]{"jpeg", "jpg", "png", "svg"};
            if (file.getContentType().equals(MimeTypeEnum.SVG.getMimeType())) {
                suffixName = MimeTypeEnum.SVG.getExtension();
            } else {
                Assert.state(Arrays.asList(imgTypes).indexOf(suffixName) != -1, "只支持jpeg,jpg,png,svg几种图片格式");
            }
            logger.info("上传图片类型是:{}", suffixName);
            // 设置文件存储路径
            String uuid = GuidUtil.getId();
            String dateDir = DateTimeUtil.getSimpleDateString();
            String path = filePath + File.separator + dateDir + File.separator + uuid + "." + suffixName;
            logger.info("--------->数据库存储图片路径:" + path);
            //图片访问路径
            String realPath = Consts.USER_UPLOAD_PATH_PREFIX + File.separator + dateDir + File.separator + uuid + "." + suffixName;
            logger.info("--------->网络访问图片路径:" + realPath);

            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                // 新建文件夹
                dest.getParentFile().mkdirs();
            }
            //文件写入
            file.transferTo(dest);
            //更新用户头像字段
//            User user = getUser();
//            user.setAvatar(realPath);
//            userService.updateUserAvatar(user);

            jsonResult.add("path", realPath);
            jsonResult.setMessage("上传成功");
            return jsonResult.toJSON();
        } catch (Exception e) {
            logger.error("上传文件失败:" + e.getMessage());
        }
        jsonResult.setMessage("上传失败");
        return jsonResult.toJSON();
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/setUserInfo")
    public String setUserInfo(@RequestBody User user) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        userService.updateUser(user);
        return jsonResult.toJSON();
    }

    /**
     * 修改个人信息
     * @param userInfoDTO
     * @return
     */
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody UpdateUserInfoDTO userInfoDTO) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        userService.updateUserInfo(userInfoDTO, getUser());
        return jsonResult.toJSON();
    }

    /**
     * 根据用户名获取用户
     *
     * @param name 用户名称
     * @return {@link String}
     */
    @PostMapping("/getUserByName")
    public String getUserByName(@RequestParam("name") String name) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        User user = userService.getUser(name);
        jsonResult.add(user);
        return jsonResult.toJSON();
    }
}
